package com.hzdl.apple.filter;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hzdl.apple.utils.HttpUtils;



/**
 * 登录拦截
 */
@WebFilter(urlPatterns = { "/user/*" }, dispatcherTypes = { DispatcherType.FORWARD, DispatcherType.REQUEST })
public class UserFilter implements Filter {

	// 拦截忽略列表
	private String[] ignoreList = {"/user/user_find","/user/user_regist"};

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		//System.out.println("++++拦截器已经拦截++++++");
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		String baseUri = request.getRequestURI();
		boolean flag = true;// 需要拦截
		for (String uri : ignoreList) {
			if (baseUri.contains(uri)) {//
				flag = false;
			}
		}

		// 未登录，重定向到登录页面
		if (flag && request.getSession().getAttribute("user") == null) {
			request.setAttribute("errMsg", "请登录之后再访问！");
			HttpUtils.forward2("/home/login", request, response);
		}

		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
